package com.etown.action;

import java.util.Iterator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.etown.dao.CommonDAO;
import com.etown.util.FileUtil;
import com.etown.util.RandomStr;
import com.etown.util.SqlMgr;
import com.etown.util.StringUtil;
import com.etown.util.email.EMailSender;
import com.etown.util.email.MailMessage;

/**
 * 用户管理相关
 * @author knight
 *
 */
public class UserMngAction extends BaseAction{
	private String userName;
	private String password;
	private String nickName;
	private String email;
	private String blogTitle;
	private int gender;
	private int industry;
	private int country;
	private int province;
	private int city;
	private String validateCode;//邮箱验证时用的字符编码
	
	/**
	 * 校验用户名是否占用
	 * @return
	 */
	public String validateUserId(){
		JSONObject result=CommonDAO.getSingle(SqlMgr.getSql("CHECK_USER_ID"), userName);
		if(result!=null){
			this.outJsonString("false");
		}else{
			this.outJsonString("true");
		}
		return null;
	}
	
	/**
	 * 校验email是否占用
	 * @return
	 */
	public String validateEmail(){
		JSONObject result=CommonDAO.getSingle(SqlMgr.getSql("CHECK_USER_EMAIL"), email);
		if(result!=null){
			this.outJsonString("false");
		}else{
			this.outJsonString("true");
		}
		return null;
	}
	
	/**
	 * 用户注册
	 * @return
	 */
	public String regist(){
		//插入用户记录
		if(StringUtil.isEmpty(blogTitle)){
			blogTitle=nickName+"的博客";
		}
		String ipAddr=this.getIpAddr();
		validateCode=RandomStr.random(32);
		CommonDAO.update(SqlMgr.getSql("ADD_USER"),userName,password,nickName,email,gender,province,city,blogTitle,industry,ipAddr,validateCode);
		
		//发送验证邮件
		EMailSender sender = new EMailSender();
		sender.setPort(25);
		sender.setUserName("damoqiongqiu");
		sender.setPassWord("xiaotao015001024");
		sender.setMailFrom("damoqiongqiu@126.com");
		
		MailMessage mail1 = new MailMessage();
		boolean mailSuccess=false;
		try {
			mail1.setMailFrom(sender.getMailFrom());
			mail1.setMailTo(email);
			mail1.setMaiSubject("来自忆唐的验证邮件");
			
			String filePath = System.getProperty("web.home")+System.getProperty("regTplHtml");
			String content=FileUtil.readAll(filePath);
			content=StringUtil.format(content, new String[]{nickName,userName,validateCode});
			mail1.setContent(content);
			mail1.saveChanges();
			mailSuccess=sender.send(mail1);
		} catch (Exception e) {
			log.error("发送验证邮件失败");
			mailSuccess=false;
		}
		if(!mailSuccess){
			this.setReqAttr("regMsg", "regFailure");
		}else{
			String mailAddr="mail."+email.substring(email.lastIndexOf("@")+1);
			this.setReqAttr("mailAddr",mailAddr);
			this.setReqAttr("regMsg", "regSuccess");
		}
		return "result";
	}
	
	/**
	 * 邮箱激活
	 * @return
	 */
	public String emailCheck(){
		if(StringUtil.isEmpty(userName)||StringUtil.isEmpty(validateCode)){
			return "failure";
		}
		
		//激活
		JSONObject result=CommonDAO.getSingle(SqlMgr.getSql("CHECK_USER_ID"), userName);
		JSONObject tempCode=result.getJSONObject("vcode");
		String temp=tempCode.toString();
		if(validateCode.equals(temp)){
			CommonDAO.update(SqlMgr.getSql("UPDATE_USER_STATE"),0,userName);
			this.setReqAttr("regMsg", "validateSuccess");
			CommonDAO.update(SqlMgr.getSql("DEL_VCODE"),userName);
		}else{
			this.setReqAttr("regMsg", "validateFailure");
		}
		return "result";
	}
	
	/**
	 * 登录
	 * @return
	 */
	public String login(){
		//校验用户名和密码
		JSONObject result=CommonDAO.getSingle(SqlMgr.getSql("LOGIN_CHECK"), userName,password);
		if(result==null){
			this.setReqAttr("errorMsg", "登录失败，用户名或密码不正确。");
			return "error";
		}else if(result.getString("state").equals("-1")){//已注册，但尚未激活
			this.setReqAttr("regMsg", "EMAIL_NOT_CHECK");
			email=result.getString("email");
			String mailAddr="mail."+email.substring(email.lastIndexOf("@")+1);
			this.setReqAttr("mailAddr",mailAddr);
			return "checkEmail";
		}else if(result!=null){
			//更新用户状态为已登录，并更新IP地址、记录最后登录时间
			String ipAddr=this.getIpAddr();
			CommonDAO.update(SqlMgr.getSql("USER_LOGIN"),ipAddr,userName);
			//加载用户的权限代码
			JSONArray permissions=CommonDAO.getList(SqlMgr.getSql("GET_USER_PERMISSION"),userName);
			if(permissions!=null){
				Iterator<JSONObject> iter=permissions.iterator();
				while(iter.hasNext()){
					JSONObject jsonObj=iter.next();
					this.setSessionAttr(jsonObj.getString("permission_code"), jsonObj.getString("permission_desc"));
				}
			}
			//取用户资料
			JSONObject userInfo=CommonDAO.getSingle(SqlMgr.getSql("GET_USER_INFO"), userName);
			if(userInfo!=null){
				this.setSessionAttr("nickName",userInfo.get("nick_name"));
				this.setSessionAttr("gradeName",userInfo.get("grade_name"));
				this.setSessionAttr("gender",userInfo.get("gender").equals("0")?"男":"女");
				this.setSessionAttr("cityId",userInfo.get("city_id"));
				this.setSessionAttr("articles",userInfo.get("articles"));
				this.setSessionAttr("posts",userInfo.get("posts"));
				this.setSessionAttr("allTimes",userInfo.get("all_times"));
				this.setSessionAttr("money",userInfo.get("money"));
				this.setSessionAttr("state",userInfo.get("state"));
				this.setSessionAttr("examGrade",userInfo.get(""));
				this.setSessionAttr("qq",userInfo.get("qq"));
			}
			//加载个人主页相关信息
			
			//设置会话参数
			this.setSessionAttr("userName", userName);
			this.setSessionAttr("nickName",result.getString("nick_name"));
			this.setSessionAttr("blogTitle",result.getString("blog_title"));
			return "success";
		}
		return "error";
	}
	
	/**
	 * 用户登出
	 * @return
	 */
	public String logout(){
		this.rmSessionAttr("userName");
		this.rmSessionAttr("nickName");
		this.rmSessionAttr("blogTitle");
		return "success";
	}
	
	/**
	 * 获取所有行业列表
	 * @return
	 */
	public String getIndustry(){
		JSONArray depts=CommonDAO.getList(SqlMgr.getSql("GET_INDUSTY"));
		System.out.println(depts.toString());
		this.outJsonString(depts.toString());
		return null;
	}
	
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getBlogTitle() {
		return blogTitle;
	}

	public void setBlogTitle(String blogTitle) {
		this.blogTitle = blogTitle;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public int getGender() {
		return gender;
	}

	public void setGender(int gender) {
		this.gender = gender;
	}

	public String getNickName() {
		return nickName;
	}

	public void setNickName(String nickName) {
		this.nickName = nickName;
	}
	

	public int getCity() {
		return city;
	}

	public void setCity(int city) {
		this.city = city;
	}

	public int getProvince() {
		return province;
	}

	public void setProvince(int province) {
		this.province = province;
	}

	public void setIndustry(int industry) {
		this.industry = industry;
	}

	public int getCountry() {
		return country;
	}

	public void setCountry(int country) {
		this.country = country;
	}

	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}
}
